import FileUploader from '@/components/FileUploader';
import PictureUploader from '@/components/PictureUploader';
import { COS_HOST } from '@/constants';
import FileConfigForm from '@/pages/Generator/Add/components/FileConfigForm';
import GeneratorMaker from '@/pages/Generator/Add/components/GeneratorMaker';
import ModelConfigForm from '@/pages/Generator/Add/components/ModelConfigForm';
import {
  addGeneratorUsingPost,
  editGeneratorUsingPost,
  getGeneratorVoByIdUsingGet,
} from '@/services/backend/generatorController';
import { useSearchParams } from '@@/exports';
import {
  ProCard,
  ProFormInstance,
  ProFormItem,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  StepsForm,
} from '@ant-design/pro-components';
import { history } from '@umijs/max';
import { message, UploadFile } from 'antd';
import { useEffect, useRef, useState } from 'react';

export default () => {
  const formRef = useRef<ProFormInstance>();
  const [searchParam] = useSearchParams();
  const id = searchParam.get('id');
  const [oldData, setOldData] = useState<API.GeneratorEditRequest>();
  const [basicInfo, setBasicInfo] = useState<API.GeneratorEditRequest>();
  const [modelConfig, setModelConfig] = useState<API.ModelConfig>();
  const [fileConfig, setFileConfig] = useState<API.FileConfig>();

  const loadData = async () => {
    if (!id) {
      return;
    }
    try {
      const res = await getGeneratorVoByIdUsingGet({
        id: id,
      });
      if (res.data) {
        const distPath = res.data.distPath;
        //@ts-ignore
        res.data.distPath = [
          {
            uid: id,
            name: '文件：' + id,
            status: 'done',
            url: COS_HOST + distPath,
            response: distPath,
          } as UploadFile,
        ];
        //@ts-ignore
        setOldData(res.data);
      }
    } catch (e: any) {
      message.error('获取失败:' + e.message);
    }
  };
  useEffect(() => {
    if (!id) {
      return;
    }
    loadData();
  }, [id]);
  const doAdd = async (values: API.GeneratorAddRequest) => {
    try {
      const res = await addGeneratorUsingPost(values);
      if (res.data) {
        message.success('创建成功');
        history.push(`/generator/detail/${res.data}`);
      }
    } catch (e: any) {
      message.success('创建失败：' + e.message);
    }
  };
  const doUpdate = async (values: API.GeneratorEditRequest) => {
    try {
      const res = await editGeneratorUsingPost(values);
      if (res.data) {
        message.success('修改成功');
        history.push(`/generator/detail/${id}`);
      }
    } catch (e: any) {
      message.success('修改失败：' + e.message);
    }
  };
  const doSubmit = async (values: API.GeneratorAddRequest) => {
    if (!values.fileConfig) {
      values.fileConfig = {};
    }
    if (!values.modelConfig) {
      values.modelConfig = {};
    }
    if (values.distPath && values.distPath.length > 0) {
      //@ts-ignore
      values.distPath = values.distPath[0].response;
    }
    if (id) {
      await doUpdate({
        ...values,
        id: id,
      });
    } else {
      await doAdd(values);
    }
  };
  return (
    <ProCard>
      {(!id || oldData) && (
        <StepsForm<API.GeneratorAddRequest | API.GeneratorEditRequest>
          formRef={formRef}
          onFinish={doSubmit}
          formProps={{
            initialValues: oldData,
          }}
        >
          <StepsForm.StepForm
            name="base"
            title="基本信息"
            onFinish={async (values) => {
              setBasicInfo(values);
              return true;
            }}
          >
            <ProFormText name="name" label="生成器名称" width="md" placeholder="生成器名称"/>
            <ProFormTextArea name="description" label="描述" width="lg" placeholder="描述"/>
            <ProFormText name="author" label="作者" width="md" placeholder="作者"/>
            <ProFormText name="basePackage" label="基础包" width="md" placeholder="基础包"/>
            <ProFormText name="version" label="版本号" width="md" placeholder="版本号"/>
            <ProFormSelect name="tags" mode="tags" label="标签" width="md" placeholder="标签"/>
            <ProFormItem label="图片" name="picture">
              <PictureUploader biz="generator_picture"/>
            </ProFormItem>
          </StepsForm.StepForm>
          <StepsForm.StepForm
            name="modelConfig"
            title="模型配置"
            onFinish={async (values) => {
              setModelConfig(values);
              return true;
            }}
          >
            <ModelConfigForm formRef={formRef} oldData={oldData}/>
          </StepsForm.StepForm>
          <StepsForm.StepForm
            name="fileConfig"
            title="文件配置"
            onFinish={async (values) => {
              setFileConfig(values);
              return true;
            }}
          >
            <FileConfigForm formRef={formRef} oldData={oldData}/>
          </StepsForm.StepForm>

          <StepsForm.StepForm
            name="dis"
            title="生成器文件"
            onFinish={async () => {
              console.log(formRef.current?.getFieldsValue());
              return true;
            }}
          >
            <ProFormItem name="distPath" label="生成器文件">
              <FileUploader biz="generator_dist" description="请上传生成器文件压缩包"/>
            </ProFormItem>
            <GeneratorMaker
              meta={{
                ...basicInfo,
                ...modelConfig,
                ...fileConfig,
              }}
            />
          </StepsForm.StepForm>
        </StepsForm>
      )}
    </ProCard>

  );
};
